import {createSlice} from "@reduxjs/toolkit";
import {AppDispatch, RootState} from "../index";
import {AuthForm} from "views/login";
import {reqInfo, reqLogin, reqLogout} from "api";
import {removeCookie, setCookie} from "utils/cookies";

interface State {
    menu: Array<any>,
    role: object,
    user: any,
    token: string
}


const initialState: State = {
    menu: [],
    role: [],
    token: '',
    user: {}
};

export const usersSlice = createSlice({
    name: "usersSlice",
    initialState,
    reducers: {
        setToken(state, action) {
            state.token = action.payload;
        },
        setUser(state, action) {
            state.user = action.payload;
        },
        setMenu(state, action) {
            state.menu = action.payload;
        },
        setRole(state, action) {
            state.role = action.payload;
        },
    },
});

const {setUser, setToken, setMenu, setRole} = usersSlice.actions;

export const selectUser = (state: RootState) => state.users.user;
export const selectMenu = (state: RootState) => state.users.menu;
export const selectRole = (state: RootState) => state.users.role;

export const login = (form: AuthForm) => (dispatch: AppDispatch) => reqLogin(form).then((res) => {
    dispatch(setToken(res.data.token))
    setCookie('mic-token', res.data.token)
})


export const logout = () => (dispatch: AppDispatch) =>
    reqLogout().then(() => {
        removeCookie('mic-token')
        dispatch(setUser(null))
        dispatch(setMenu(null))
        dispatch(setRole(null))
    });


export const getInfo = () => (dispatch: AppDispatch) =>
    reqInfo().then(({data}) => {
        dispatch(setUser(data.user))
        dispatch(setMenu(data.menu))
        dispatch(setRole(data.role))
    });


